<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<div>
    <div>
        <div>接收消息:</div>
        <div id="meg_box" style="background-color: aqua;"></div>
    </div>
    <div>
        <div>发送消息:</div>
        <input type="text" id="msg_context"/>
        <input type="button" value="发送" onclick="CHAT.chat()"/>
    </div>

</div>
<script type="application/javascript">

    window.CHAT = {
        socket: null,
        init: function () {
            if (window.WebSocket) {
                CHAT.socket = new WebSocket("ws://127.0.0.1:8081/ws");
                CHAT.socket.onopen = function () {
                    console.log("连接建立成功.");
                },
                    CHAT.socket.onclose = function () {
                        console.log("连接关闭.");
                    },
                    CHAT.socket.onerror = function () {
                        console.log("发生错误!");
                    },
                    CHAT.socket.onmessage = function (data) {
                        console.log("接收到消息");
                        console.log(data.data);
                        var msg = document.getElementById("meg_box");
                        var html = msg.innerHTML;
                        msg.innerHTML = html + data.data + " <br />";
                    }
            } else {
                alert("浏览器不支持WebSocket协议!!!");
            }
        },
        chat: function () {
            var mes = document.getElementById("msg_context");
            console.log(mes.value);
            CHAT.socket.send(mes.value);
        }
    }

    CHAT.init();
</script>
</body>
</html>